import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:get/get.dart';
import '../models/post.dart';
import '../models/comment.dart';
import '../data/data_repository.dart';
import '../widgets/full_screen_image_viewer.dart';
import '../widgets/image_grid.dart';
import '../routes/routes.dart'; // 添加 AppRoutes 导入

class PostDetailPage extends StatefulWidget {
  final Post? post;

  const PostDetailPage({Key? key, this.post}) : super(key: key);

  @override
  _PostDetailPageState createState() => _PostDetailPageState();
}

class _PostDetailPageState extends State<PostDetailPage> {
  final TextEditingController _commentController = TextEditingController();
  bool _isLiked = false;
  int _likesCount = 0;
  List<Comment> _comments = [];
  late Post _post;
  final FocusNode _commentFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // 安全地从Get参数中获取post
    if (widget.post != null) {
      _post = widget.post!;
    } else if (Get.arguments != null && Get.arguments is Map && Get.arguments.containsKey('post')) {
      _post = Get.arguments['post'];
    } else {
      // 如果无法获取post，创建一个默认的空post或者显示错误
      _post = Post(
        postId: 'error',
        userId: 'error',
        userNickname: '未知用户',
        userAvatarUrl: 'https://via.placeholder.com/150',
        title: '加载失败',
        content: '无法加载帖子内容',
        images: [],
        comments: [],
        ctime: DateTime.now(),
        likesCount: 0,
        commentsCount: 0,
        isLiked: false,
        isFollowed: false,
      );
      
      // 可以选择显示错误提示或返回上一页
      WidgetsBinding.instance.addPostFrameCallback((_) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('帖子加载失败')),
        );
        // 如果需要，可以自动返回上一页
        // Get.back();
      });
    }
    
    // 初始化其他状态
    _isLiked = _post.isLiked;
    _likesCount = _post.likesCount;
    _comments = List.from(_post.comments); // 创建评论列表的副本
  }

  @override
  void dispose() {
    _commentController.dispose();
    _commentFocusNode.dispose();
    super.dispose();
  }

  void _toggleLike() {
    setState(() {
      _isLiked = !_isLiked;
      _likesCount += _isLiked ? 1 : -1;
      
      // 更新原始帖子对象的点赞状态
      _post.isLiked = _isLiked;
      _post.likesCount = _likesCount;
    });
  }

  void _addComment() {
    if (_commentController.text.trim().isEmpty) return;
    
    final newComment = Comment(
      commentId: 'comment_${DateTime.now().millisecondsSinceEpoch}',
      userId: 'current_user_id', // 实际应用中应该使用当前登录用户的ID
      userNickname: '当前用户', // 实际应用中应该使用当前登录用户的昵称
      userAvatarUrl: 'https://via.placeholder.com/150/comment0',
      content: _commentController.text.trim(),
      ctime: DateTime.now(),
    );
    
    setState(() {
      _comments.insert(0, newComment);
      _post.comments = List.from(_comments); // 更新Post对象中的评论列表
      _post.commentsCount = _comments.length; // 更新评论数
    });
    
    _commentController.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('帖子详情'),
        elevation: 0.5,
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () {
              // 分享功能实现
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('分享功能待实现')),
              );
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 主体内容（可滚动）
          Expanded(
            child: ListView(
              padding: const EdgeInsets.all(16.0),
              children: [
                // 用户信息区域
                _buildUserInfoSection(),
                
                const SizedBox(height: 16.0),
                
                // 帖子内容区域
                _buildPostContentSection(),
                
                const SizedBox(height: 16.0),
                
                // 帖子互动数据
                _buildInteractionStats(),
                
                const Divider(height: 32.0),
                
                // 评论区标题
                const Row(
                  children: [
                    Icon(Icons.comment, size: 18, color: Colors.grey),
                    SizedBox(width: 8.0),
                    Text(
                      '全部评论',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                
                const SizedBox(height: 16.0),
                
                // 评论列表
                _buildCommentsList(),
              ],
            ),
          ),
          
          // 底部评论输入框
          _buildCommentInputBar(),
        ],
      ),
    );
  }

  // 用户信息区域
  Widget _buildUserInfoSection() {
    return Row(
      children: [
        // 用户头像 - 添加点击事件跳转到用户详情页
        GestureDetector(
          onTap: () {
            Get.toNamed(
              AppRoutes.userProfile,
              arguments: {
                'userId': _post.userId,
                'userNickname': _post.userNickname,
                'userAvatarUrl': _post.userAvatarUrl,
              }
            );
          },
          child: CircleAvatar(
            radius: 20,
            backgroundImage: NetworkImage(_post.userAvatarUrl),
          ),
        ),
        const SizedBox(width: 12),
        
        // 用户名和发布时间
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    _post.userNickname,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(width: 8),
                  // 关注按钮
                  _buildFollowButton(),
                ],
              ),
              const SizedBox(height: 4),
              Text(
                DateFormat('yyyy-MM-dd HH:mm').format(_post.ctime),
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
        
        // 更多操作按钮
        IconButton(
          icon: const Icon(Icons.more_horiz, color: Colors.grey),
          onPressed: () {
            // 显示更多操作菜单
            showModalBottomSheet(
              context: context,
              builder: (context) => Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ListTile(
                    leading: const Icon(Icons.report),
                    title: const Text('举报'),
                    onTap: () {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('举报功能待实现')),
                      );
                    },
                  ),
                  ListTile(
                    leading: const Icon(Icons.block),
                    title: const Text('屏蔽此用户'),
                    onTap: () {
                      Navigator.pop(context);
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('屏蔽功能待实现')),
                      );
                    },
                  ),
                ],
              ),
            );
          },
        ),
      ],
    );
  }

  // 关注按钮 - 移到类级别
  Widget _buildFollowButton() {
    return OutlinedButton(
      onPressed: () {
        setState(() {
          _post.isFollowed = !_post.isFollowed; // 更新本地Post对象
        });
      },
      style: OutlinedButton.styleFrom(
        side: BorderSide(
          color: _post.isFollowed ? Colors.grey : Theme.of(context).primaryColor,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.0),
        ),
      ),
      child: Text(
        _post.isFollowed ? '已关注' : '关注',
        style: TextStyle(
          color: _post.isFollowed ? Colors.grey : Theme.of(context).primaryColor,
        ),
      ),
    );
  }

  // 帖子内容区域
  Widget _buildPostContentSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 帖子标题
        if (_post.title.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: Text(
              _post.title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        
        // 帖子内容
        Text(
          _post.content,  // 使用 _post 而不是 widget.post
          style: const TextStyle(fontSize: 16),
        ),
        
        const SizedBox(height: 16.0),
        
        // 图片区域
        if (_post.images.isNotEmpty)  // 使用 _post 而不是 widget.post
          _buildImageGrid(_post.images),
          
        // 视频区域
        if (_post.videoUrl != null)  // 使用 _post 而不是 widget.post
          Container(
            height: 200,
            width: double.infinity,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Stack(
              alignment: Alignment.center,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.network(
                    'https://via.placeholder.com/400x200/000000/FFFFFF?text=Video+Thumbnail',
                    fit: BoxFit.cover,
                    width: double.infinity,
                  ),
                ),
                Icon(
                  Icons.play_circle_fill,
                  size: 50,
                  color: Colors.white.withOpacity(0.8),
                ),
              ],
            ),
          ),
      ],
    );
  }

  // 图片网格
  Widget _buildImageGrid(List<String> images) {
    // 根据图片数量决定布局
    if (images.length == 1) {
      // 单张图片，大图显示
      return GestureDetector(
        onTap: () => _openFullScreenImage(images, 0),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.network(
            images[0],
            fit: BoxFit.cover,
          ),
        ),
      );
    } else {
      // 多张图片，使用ImageGrid组件
      return ImageGrid(images: images);
    }
  }

  // 打开全屏图片查看器
  void _openFullScreenImage(List<String> images, int initialIndex) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => FullScreenImageViewer(
          images: images,
          initialIndex: initialIndex,
        ),
      ),
    );
  }

  // 帖子互动数据
  Widget _buildInteractionStats() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        // 点赞按钮
        _buildInteractionButton(
          icon: _isLiked ? Icons.favorite : Icons.favorite_border,
          label: '$_likesCount 赞',
          color: _isLiked ? Colors.red : Colors.grey,
          onTap: _toggleLike,
        ),
        
        // 评论按钮
        _buildInteractionButton(
          icon: Icons.comment_outlined,
          label: '${_comments.length} 评论',
          color: Colors.grey,
          onTap: () {
            // 滚动到评论区
          },
        ),
        
        // 转发按钮
        _buildInteractionButton(
          icon: Icons.repeat,
          label: '转发',
          color: Colors.grey,
          onTap: () {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('转发功能待实现')),
            );
          },
        ),
      ],
    );
  }

  // 互动按钮
  Widget _buildInteractionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8.0),
        child: Row(
          children: [
            Icon(icon, color: color, size: 20),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(color: color, fontSize: 14),
            ),
          ],
        ),
      ),
    );
  }

  // 评论列表
  Widget _buildCommentsList() {
    if (_comments.isEmpty) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 32.0),
          child: Text(
            '暂无评论，快来抢沙发吧！',
            style: TextStyle(color: Colors.grey),
          ),
        ),
      );
    }

    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: _comments.length,
      separatorBuilder: (context, index) => const Divider(height: 1),
      itemBuilder: (context, index) {
        final comment = _comments[index];
        return Padding(
          padding: const EdgeInsets.symmetric(vertical: 12.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 评论用户头像
              CircleAvatar(
                radius: 18,
                backgroundImage: NetworkImage(comment.userAvatarUrl),
              ),
              const SizedBox(width: 12),
              
              // 评论内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名和评论时间
                    Row(
                      children: [
                        Text(
                          comment.userNickname,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 14,
                          ),
                        ),
                        const Spacer(),
                        Text(
                          DateFormat('MM-dd HH:mm').format(comment.ctime),
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                    
                    // 评论内容
                    Text(
                      comment.content,
                      style: const TextStyle(fontSize: 14),
                    ),
                    
                    const SizedBox(height: 8),
                    
                    // 评论操作按钮
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            // 回复评论
                            _commentController.text = '@${comment.userNickname} ';
                            FocusScope.of(context).requestFocus(FocusNode());
                          },
                          child: const Text(
                            '回复',
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 12,
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        GestureDetector(
                          onTap: () {
                            // 点赞评论
                          },
                          child: const Row(
                            children: [
                              Icon(Icons.thumb_up_outlined, size: 14, color: Colors.grey),
                              SizedBox(width: 4),
                              Text(
                                '点赞',
                                style: TextStyle(
                                  color: Colors.grey,
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 底部评论输入框
  Widget _buildCommentInputBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            blurRadius: 4,
            offset: const Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        children: [
          // 评论输入框
          Expanded(
            child: TextField(
              controller: _commentController,
              focusNode: _commentFocusNode,  // 添加焦点节点
              decoration: InputDecoration(
                hintText: '写评论...',
                hintStyle: TextStyle(color: Colors.grey[400]),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey[100],
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              ),
              maxLines: 1,
            ),
          ),
          const SizedBox(width: 8),
          
          // 发送按钮
          IconButton(
            icon: const Icon(Icons.send, color: Colors.blue),
            onPressed: _addComment,
          ),
        ],
      ),
    );
  }
}